package datatypes.list;

import java.util.Iterator;

public class DoublyLinkedListIterator<E> implements Iterator<E>, NodeStakeholder<E> {
	
	private Node<E> next;
	
	public DoublyLinkedListIterator(Node<E> starter) {
		if (starter != null) {
			starter.registerAsStakeholder(this);
		}
		this.next = starter;
	}

	@Override
	public boolean hasNext() {
		return next != null;
	}

	@Override
	public E next() {
		if (next == null) {
			return null;
		}
		E returnValue = next.element;
		next.cancelStakeholderRegistration(this);
		next = next.next;
		if (next != null) {
			next.registerAsStakeholder(this);
		}
		return returnValue;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public void updateNode(Node<E> node) {
//		if (next != null) {
//			next.cancelStakeholderRegistration(this);
//		}
		if (node != null) {
			node.registerAsStakeholder(this);
		}
		next = node;
	}
}
